package com.hoas.quickstart.threads.chapter03.chapter03_3;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class ThreadLocalTest2 {

    private static ThreadLocal<Map> mapThreadLocal = new ThreadLocal<Map>() {
        public Map initialValue() {
            return Collections.emptyMap();
        }

    };
    private static Map<String, String> staticMap = new HashMap<String, String>() {{
        put("initKey", "initValue");
    }};

    public static void main(String[] args) throws InterruptedException {
        // 主线程将staticMap设置到当前线程中
        mapThreadLocal.set(staticMap);

        System.out.println(String.format("%s---------initKey->%s",
                Thread.currentThread().getName(), mapThreadLocal.get().get("initKey")));

        Thread thread_0 = new Thread(() -> {

            System.out.println(String.format("%s-----initKey->%s",
                    Thread.currentThread().getName(), mapThreadLocal.get().get("initKey")));
            // 线程0，修改staticMap的值
            staticMap.put("initKey", "newValue");
        });
        thread_0.start();
        thread_0.join();

        System.out.println(String.format("%s---------initKey->%s",
                Thread.currentThread().getName(), mapThreadLocal.get().get("initKey")));

        Thread thread_1 = new Thread(() -> {
            // 线程1将新创建的map对象设置到线程1中
            mapThreadLocal.set(new HashMap<String, String>() {{
                put("initKey", "newerValue");
            }});
            System.out.println(String.format("%s-----initKey->%s",
                    Thread.currentThread().getName(), mapThreadLocal.get().get("initKey")));
        }, "thread-1");
        thread_1.start();
        thread_1.join();

        System.out.println(String.format("%s---------initKey->%s",
                Thread.currentThread().getName(), mapThreadLocal.get().get("initKey")));
    }


}
